package com.library.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.library.common.Result;
import com.library.entity.User;
import com.library.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * 用户管理控制器
 */
@Tag(name = "用户管理")
@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
public class UserController {
    
    private final UserService userService;
    
    @Operation(summary = "分页查询用户")
    @SaCheckRole("ADMIN")
    @GetMapping
    public Result<Page<User>> pageUsers(@RequestParam(defaultValue = "1") Integer current,
                                        @RequestParam(defaultValue = "10") Integer size,
                                        @RequestParam(required = false) String username,
                                        @RequestParam(required = false) String role) {
        Page<User> page = userService.pageUsers(current, size, username, role);
        return Result.success(page);
    }
    
    @Operation(summary = "获取用户详情")
    @SaCheckRole("ADMIN")
    @GetMapping("/{id}")
    public Result<User> getUser(@PathVariable Long id) {
        User user = userService.getById(id);
        user.setPassword(null);
        return Result.success(user);
    }
    
    @Operation(summary = "更新用户")
    @SaCheckRole("ADMIN")
    @PutMapping("/{id}")
    public Result<Void> updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        user.setPassword(null); // 不允许通过此接口修改密码
        userService.updateById(user);
        return Result.success("更新成功");
    }
    
    @Operation(summary = "删除用户")
    @SaCheckRole("ADMIN")
    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(@PathVariable Long id) {
        userService.removeById(id);
        return Result.success("删除成功");
    }
    
    @Operation(summary = "启用/禁用用户")
    @SaCheckRole("ADMIN")
    @PutMapping("/{id}/status")
    public Result<Void> updateStatus(@PathVariable Long id, @RequestParam Integer status) {
        User user = new User();
        user.setId(id);
        user.setStatus(status);
        userService.updateById(user);
        return Result.success("操作成功");
    }
}

